package com.newflypig.jblog.controller;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.baidu.ueditor.ActionEnter;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
public class BaseController {
	@Autowired  
    private Producer captchaProducer;

	@RequestMapping({"/index.html","/","/index.jsp"})
	public String hello(Model model){
		return "redirect:article/articles";
	}
	
	/**
	 * 返回UEditor的控制JSON
	 */
	@RequestMapping({"/ueditorcontroller.json"})
	public void ueditorController(HttpServletRequest request,HttpServletResponse response){
		try {
			request.setCharacterEncoding( "utf-8" );
			response.setHeader( "Content-Type" , "text/html" );
			String rootPath = request.getSession().getServletContext().getRealPath("/");
			response.getWriter().write(new ActionEnter( request, rootPath ).exec() );
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * kaptcha验证码输出 
	 */
	@RequestMapping(value = "captcha-image")  
    public ModelAndView getKaptchaImage(HttpSession session , HttpServletResponse response) throws Exception {  
        response.setDateHeader("Expires", 0);  
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
        response.setHeader("Pragma", "no-cache");  
        response.setContentType("image/jpeg");  
         
        String capText = captchaProducer.createText();  
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);  
         
        BufferedImage bi = captchaProducer.createImage(capText);  
        ServletOutputStream out = response.getOutputStream();  
        ImageIO.write(bi, "jpg", out);  
        try {  
            out.flush();  
        } finally {  
            out.close();  
        }  
        return null;  
    }  
}
